package com.wx.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.wx.dao.SysIpWhiteMapper;
import com.wx.entity.SysIpWhite;
import com.wx.entity.SysIpWhiteExample;
import com.wx.flag.IPWhiteEnum;
import com.wx.service.SysIPWhiteService;
import com.wx.util.IPUtils;

@Service
public class SysIPWhiteServiceImpl implements SysIPWhiteService {

	@Resource
	private SysIpWhiteMapper ipWhiteMapper;

	@Override
	public int countByExample(SysIpWhiteExample example) {
		return ipWhiteMapper.countByExample(example);
	}

	@Override
	public int deleteByExample(SysIpWhiteExample example) {
		return ipWhiteMapper.deleteByExample(example);
	}

	@Override
	public int deleteByPrimaryKey(Integer id) {
		return ipWhiteMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(SysIpWhite record) {
		return ipWhiteMapper.insertSelective(record);
	}

	@Override
	public List<SysIpWhite> selectByExample(SysIpWhiteExample example) {
		return ipWhiteMapper.selectByExample(example);
	}

	@Override
	public SysIpWhite selectByPrimaryKey(Integer id) {
		return ipWhiteMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByExample(SysIpWhite record, SysIpWhiteExample example) {
		return ipWhiteMapper.updateByExampleSelective(record, example);
	}

	@Override
	public int updateByPrimaryKey(SysIpWhite record) {
		return ipWhiteMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public boolean verifyIP(String ip) {
		SysIpWhiteExample example = new SysIpWhiteExample();
		example.createCriteria().andIsValidEqualTo(IPWhiteEnum.IS_VALID_YSE.getValue());
		List<SysIpWhite> list = this.selectByExample(example);
		//如果没有任何数据，就通过
		if(list.isEmpty()){
			return true;
		}
		//如果有一次匹配，就通过
		String beginIp, endIp, sectionIp;
		for (SysIpWhite ips : list) {
			try {
				beginIp = ips.getBeginIp();
				endIp = ips.getEndIp();
				sectionIp = beginIp.concat("-").concat(endIp);
				if (IPUtils.ipExistsInRange(ip, sectionIp)) {
					return true;
				}
			} catch (Exception e) {
				continue;//如果有异常就跳过这个验证
			}
		}
		return false;
	}

}
